<?php

#<editor-fold defaultstate="collapsed" desc="CCore::Using">
CCore::Using('socket.inc.streams.inc.interface');
#</editor-fold>

class CCoreSocketIncStreamsTestFiles implements ICoreSocketIncStreams
{
	#<editor-fold defaultstate="collapsed" desc="private">
	/**
	 * @var	resource
	 */
	private $_rFile;
	
	/**
	 * @var	string
	 */
	private $_sStreamData;

	/**
	 * @var	string
	 */
	private $_sCurrentFile;
	#</editor-fold>

	/**
	 * @param	string	$sStreamData
	 * @return	CCoreSocketIncStreamsTestFiles
	 */
	public function __construct($sStreamData)
	{
		CCore::CheckTypes(array('$sStreamData'));

		$this->_sStreamData = $sStreamData;
		$this->_sCurrentFile = '';
		$this->_rFile = null;
	}

	/**
	 * @param	string	$sHost
	 * @param	int		$iPort
	 * @param	int		&$iErrorNo
	 * @param	string	&$sErrorStr
	 * @param	int		$iConnectTimeOut
	 * @return	bool
	 */
	public function Open($sHost, $iPort, &$iErrorNo, &$sErrorStr, $iConnectTimeOut)
	{
		CCore::CheckTypes(array('$sHost', '$iPort', '$iErrorNo', '$sErrorStr', '$iConnectTimeOut'));
		
		$this->_sCurrentFile = '_connect_.txt';
		return $this->IsConnected();
	}

	/**
	 * @return	void
	 */
	public function Close()
	{
		$this->_sCurrentFile = '';
		if (is_resource($this->_rFile))
		{
			@fclose($this->_rFile);
		}
		$this->_rFile = null;
		return true;
	}

	/**
	 * @return	bool
	 */
	public function IsConnected()
	{
		return strlen($this->_sCurrentFile) > 0 && file_exists($this->_sStreamData.'/'.$this->_sCurrentFile);
	}

	/**
	 * @param	string	$sLine
	 * @return	bool
	 */
	public function Write($sLine)
	{
		CCore::CheckTypes(array('$sLine'));

		if (is_resource($this->_rFile))
		{
			@fclose($this->_rFile);
		}
		$this->_rFile = null;
		
		$this->_sCurrentFile = $this->_getWriteFileName($sLine);
		return $this->IsConnected();
	}

	/**
	 * @return	string | false
	 */
	public function Read()
	{
		if (is_resource($this->_rFile))
		{
			return @fgets($this->_rFile, 512);
		}
		else if ($this->IsConnected())
		{
			$this->_rFile = @fopen($this->_sStreamData.'/'.$this->_sCurrentFile, 'rb');
			if (is_resource($this->_rFile))
			{
				return @fgets($this->_rFile, 512);
			}
		}

		return false;
	}

	/**
	 * @return	array | false
	 */
	public function Status()
	{
		return array();
	}

	/**
	 * @param	int		$iSocketTimeOut
	 * @param	bool	$bSocketBlocking
	 */
	public function SetTimeAndBlocking($iSocketTimeOut, $bSocketBlocking)
	{
		CCore::CheckTypes(array('$iSocketTimeOut', '$bSocketBlocking'));
	}

	/**
	 * @param	string	$sLine
	 * @return	string
	 */
	private function _getWriteFileName($sLine)
	{
		CCore::CheckTypes(array('$sLine'));

		$sLine = substr(trim($sLine), 0, 16);
		$sLine = preg_replace('/[^a-zA-Z0-9]/', '_', $sLine);
		$sLine = preg_replace('/[_]+/', '_', $sLine);
		return $sLine.'.txt';
	}
}